package cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools;

import java.util.Comparator;
import java.util.List;
import java.util.Collections;

public class LockUilts {

	private static LockComparator lockComparator = new LockComparator();

	public static String addlock(String lockNode, String localId, String reqTime) {
		return lockNode + "/" + localId + "_" + reqTime;
	}

	public static String getlock(String lockNode, String localLock) {
		return lockNode + "/" + localLock;
	}

	public static String getlockId(String lock) {
		lock = lock.substring(0, lock.indexOf("_"));
		return lock;
	}

	public static Long parselockTime(String localLock) {
		String time = localLock.substring(localLock.indexOf("_")+1, localLock.length());

		return Long.parseLong(time);
	}

	public static String firstlocalLock(List<String> currentChilds) {
		Collections.sort(currentChilds, lockComparator);
		return currentChilds.get(0);
	}

	public static boolean isLocalLock(String localLock, List<String> currentChilds) {
		String lock = LockUilts.firstlocalLock(currentChilds);
		return localLock.equals(LockUilts.getlockId(lock));
	}
	
	public static boolean isLocalLock(String localLock, String inLock) {
		String inLock_ = inLock.substring(0,inLock.indexOf("_"));
		return localLock.equals(inLock_);
	}

}

class LockComparator implements Comparator<String> {

	@Override
	public int compare(String o1, String o2) {

		return LockUilts.parselockTime(o1).compareTo(LockUilts.parselockTime(o2));
	}

}
